<template>
	<view class="content">
		<u-form :model="form" ref="uForm" :error-type="['toast']">
			<u-form-item label="原手机号:" labelWidth="160">{{baseInfo.phone}}</u-form-item>
			
			<u-form-item label="新手机号:" labelWidth="160"  prop="new_phone">
				<u-input placeholder="请输入手机号" v-model="form.new_phone" />
			</u-form-item>
			
			<u-form-item label="验证码:" labelWidth="160"  prop="code">
				<u-input placeholder="请输入验证码" v-model="form.code" />
				<u-verification-code :seconds="seconds"  ref="uCode" 
						@change="codeChange"></u-verification-code>
				<u-button slot="right" type="primary" size="mini" @click="getCode">{{tips}}</u-button>
			</u-form-item>
			<u-button type="primary" @click="submit">确定</u-button>
		</u-form>
	</view>
	
</template>
<script>
import {toast, useRouter} from '@/utils/utils.js'	
export default {
	data() {
		return {
			baseInfo: {
			  phone : '',
			},
			form: {
				new_phone: '',
				code: ''
			},
			rules: {
				new_phone: [
					{
						required: true,
						message: '请输入手机号',
						trigger: 'blur,change'
					},
					{
						validator: (rule, value, callback) => {
							return this.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						trigger: ['change','blur'],
					}
				],
				code: [
					{
						required: true,
						min: 4,
						type: 'number',
						message: '验证码格式错误',
						trigger: 'change'
					}
				]
			},
			seconds: 60,
			refCode: null,
			tips:'获取验证码'
		};
	},
	onReady() {
			this.$refs.uForm.setRules(this.rules);
	},
	onLoad(){
		this.getUserInfo()
	},
	methods: {
		submit(){
			this.$refs.uForm.validate(valid => {
				if (valid) {
					//验证通过，执行TODO
					this.$api.phoneBind(this.form).then(res => {
						if (res.code == 0) {
							toast(res.msg)
							setTimeout(()=>{
								uni.navigateBack()
							},500) 
						} else {
							toast(res.msg)
						}
					}) 
				} else {
					console.log('验证失败');
				}
			});
		},
		getUserInfo() {
			this.$api.baseInfo().then(res => {
				this.baseInfo = res.data
			})
		},
		codeChange(text) {
			this.tips = text;
		},
		getCode() {
			if(this.$refs.uCode.canGetCode) {
				// 模拟向后端请求验证码
				uni.showLoading({
					title: '正在获取验证码'
				})
				setTimeout(() => {
					uni.hideLoading();
					// 这里此提示会被this.start()方法中的提示覆盖
					this.$u.toast('验证码已发送');
					// 通知验证码组件内部开始倒计时
					this.$refs.uCode.start();
				}, 2000);
			} else {
				this.$u.toast('倒计时结束后再发送');
			}
		}
	}
};
</script>

<style lang="scss" scoped>
	.content{padding:35rpx}
</style>